<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>常用语</title>
    <#include "/pubHeadStyle.html">
</head>
<body>
<div style="height: 100%;">
    <div class="tablesize roles" style=" padding:10px">
        <table id="taskApprovalItemsTable" lay-filter="taskApprovalItemsTable"></table>
    </div>
</div>
<script type="text/html" id="headerToolsBar">
    <div class="ccpui-enterSel">
    <div class="layui-btn-container">
        <a class="layui-btn layui-btn-sm" lay-event="query">
            <i class="layui-icon layui-icon-search"></i>
            <span>查询</span>
        </a>
        <a class="layui-btn layui-btn-sm" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>
            <span>添加</span>
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">
            <i class="layui-icon layui-icon-delete"></i>
            <span>删除</span>
        </a>
        <a class="layui-btn layui-btn-sm" lay-event="reset">
            <i class="layui-icon layui-icon-refresh"></i>
            <span>重置</span>
        </a>
    </div>

    <form class="layui-form" action="" lay-filter="instanceQueryForm" style="margin-top:10px">
        <div class="table-top-filter">
            <div class="table-filter-alone">
                <label class="layui-form-label">常用语</label>
                <input id="hiddenText" type="text" style="display:none" />
                <input type="text" name="Q_expression_SL" id="expressionName" class="layui-input filter-value"
                       placeholder="常用语"/>
            </div>
            <#if currUserId=='orgResourcesManager' >
            <div class="table-filter-alone">
                    <span class="label">流程分类:</span>
                    <select name="Q_typeId_L" class="selectTypeId" >
                        <option value="">全部</option>
                    </select>
            </div>
            </#if>
        </div>
    </form>
    </div>
</script>

<script type="text/html" id="managerBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','table', 'layer', 'util', 'commons', 'setter', 'totalFilter', 'common', 'laydate','admin'], function () {
        var table = layui.table;
        var setter = layui.setter;
        var common = layui.common;
        var commons = layui.commons;
        var totalFilter = layui.totalFilter;
        var $ = layui.$;
        common.tableSort('taskApprovalItemsTable');
        var isAdmin = "${isAdmin?string ('true','false')}";
        var modelMap=[];
        var modelTypeMap=[];
        var globalTypeList=[];
        var tableH = commons.tabHeight();

        renderTable(serverPath.workflowPath + setter.workflowLinkPath + "taskApprovalItems/list");
        function renderTable(url) {
            table.render({
                elem: "#taskApprovalItemsTable"
                , title: '常用语'
                , toolbar: '#headerToolsBar'
                ,height:tableH
                // ,data:data
                , page: true

                , url:url
                , parseData:function(res){
                    //1、与常用语相关联的流程和流程分类
                    modelMap = res.data.modelMap;
                    modelTypeMap = res.data.modelTypeMap;

                    //2、所有的流程分类,在超级管理员时实现
                    <#if currUserId=='orgResourcesManager' >
                        globalTypeList = res.data.globalTypeList ;
                        $.each(globalTypeList,function (index,val) {
                            $("select[name=Q_typeId_L]").parent().show();
                            $("select[name=Q_typeId_L]").append('<option value="'+val.typeId+'">'+val.typeName+'</option>');
                        })
                    </#if>
        /**
        * 2019-12-56 新增逻辑：依据查询条件进行查询后，修改table数据渲染逻辑，使得查询条件不被清除
        * 这个函数非常实用，是2.4.0版本新增的，当后端返回的数据格式不符合layuitable需要的格式，用这个函数对返回的数据做处理，在2.4.0版本之前，只能通过修改table源码来解决这个问题
        */
                    //3、重新处理查询结果
                    return {
                        code:res.code,
                        msg:res.msg,
                        count:res.count, //总页数，用于分页
                        data:res.data.taskApprovalList
                    }
                }

                ,defaultToolbar: ['filter', 'print']
                , cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    , { field: 'itemId', title: '隐藏ID', hide: true }
                    , { field: 'expression', title: '常用语', align: 'center' }
                    , {
                        field: 'type', title: '作用范围', sort: true, align: 'center', templet: function (d) {
                            switch (d.type) {
                                case 1:
                                    return "<span style='color: green'>系统全局</span>";
                                case 2:
                                    return "流程分类";
                                case 3:
                                    return "流程定义";
                                case 4:
                                    return "个人常用语";
                            }
                        }
                    }
                    , {
                        field: 'typeName', title: '作用对象', sort: true, align: 'center', templet: function (d) {
                            if (d.type == 1) {
                                return "所有流程"
                            };
                            if (d.type == 2){
                                var str = "";
                                var value = d.typeId
                                if (modelTypeMap[value]){
                                    str = modelTypeMap[value];
                                }else {
                                    str = '-'
                                }
                                return str;
                            };
                            if (d.type == 3) {
                                var str = "";
                                var value = d.modelKey
                                if (modelMap[value]){
                                    str = modelMap[value];
                                }else {
                                    str = '-'
                                }
                                return str;
                            }
                            if (d.type == 4) {
                                return "所有流程"
                            }
                            ;
                        }
                    }
                    , {title: '管理',width:100, align: 'center', toolbar: '#managerBar'}
                ]]
                ,done:function () {
                    common.tableSelectCon('.ccpui-enterSel .layui-form input','a[lay-event=query]','.ccpui-enterSel')
                }
            })
            totalFilter.init('taskApprovalItemsTable');
        }

            //监听工具条
            table.on('tool(taskApprovalItemsTable)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

                if(layEvent === 'del'){ //删除
                    layer.confirm('确认删除吗？', function(index){
                        //向服务端发送删除指令
                        $.ajax({
                            url: serverPath.workflowPath + setter.workflowLinkPath + 'taskApprovalItems/del',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                ids: obj.data.itemId
                            },
                            success: function(data){
                                if(data.code !== 0){
                                    layer.msg(data.msg, {time: 2500, icon:5});
                                    return false;
                                }
                                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                layer.close(index);
                                layer.msg(data.msg, {time: 5000, icon:6});
                                common.tableConditionRender("taskApprovalItemsTable","instanceQueryForm",{where:{}},false);
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.alert("删除失败！" + XMLHttpRequest.status);
                            }
                        });
                    });
                } else if(layEvent === 'LAYTABLE_TIPS'){
                    layer.alert('Hi，头部工具栏扩展的右侧图标。');
                }
            });
            // 监听头工具栏事件
            table.on('toolbar(taskApprovalItemsTable)',function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data; //获取选中行数据
                switch (obj.event) {
                    case 'query':
                        common.tableConditionRender("taskApprovalItemsTable","instanceQueryForm",{where:{}},false);
                        break;
                    case 'add':
                        addHandle();
                        break;
                    case 'del':
                        if(data.length === 0){
                            layer.msg("请选择一项数据!", {time: 2500, icon:5});
                            return false;
                        }
                        var ids = $.map(data,function(v){
                            return v.itemId;
                        });
                        layer.confirm("确认删除吗?",{icon:0},function(index){
                            $.ajax({
                                url: serverPath.workflowPath + setter.workflowLinkPath + 'taskApprovalItems/del',
                                type: 'post',
                                dataType: 'json',
                                data: {
                                    ids: ids.toString()
                                },
                                success: function(data){
                                    if(data.code !== 0){
                                        layer.msg(data.msg, {time: 2500, icon:5});
                                        return false;
                                    }
                                    layer.close(index);
                                    layer.msg(data.msg, {time: 5000, icon:6});
                                    common.tableConditionRender("taskApprovalItemsTable","instanceQueryForm",{where:{}},false);
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    layer.alert("删除失败！" + XMLHttpRequest.status);
                                }
                            });
                        });
                        break;
                    case 'reset':
                        common.tableConditionRender("taskApprovalItemsTable","instanceQueryForm",{where:{}},true);
                        break;
                }
            });
            // 新增弹窗
            function addHandle(){
                parent.layer.open({
                    type: 2,
                    title: '新增',
                    area: ['790px', '560px'],
                    content: serverPath.workflowPath + setter.workflowLinkPath + 'taskApprovalItems/view/edit?&isAdmin='+isAdmin,
                    skin: 'btn-class',
                    btn: ['保存','取消'],
                    btnAlign: 'c',
                    yes: function(index,layero){
                        //获取iframe的body元素
                        var body = parent.layer.getChildFrame('body',index);
                        //得到iframe页的窗口对象
                        var iframeWin = parent.window[layero.find('iframe')[0]['name']];
                        var type = body.find("div.layui-show input[name=type]").val();
                        var approvalItemOK = validateLength(body.find("div.layui-show textarea[name=approvalItem]").val());
                        var flowTypeId,defKey;
                        if(body.find(".layui-show").find("textarea").val()==""){
                            parent.layer.msg("常用语不能为空！", {time: 2500, icon:5});
                        }else {
                            if(approvalItemOK){
                                if(type==2){
                                    var aryTypeId = [];
                                    body.find("#flowTypeArray>span").each(function (i,ch){
                                        aryTypeId.push($(ch).attr("value"));
                                    });
                                    flowTypeId=aryTypeId.join(",");
                                }else if(type==3){
                                    var aryDefKey = [];
                                    body.find("#referDefinitionSpan>span").each(function (i,ch){
                                        aryDefKey.push($(ch).attr("value"));
                                    });
                                    defKey=aryDefKey.join(",");
                                }
                                $.ajax({
                                    url: serverPath.workflowPath + setter.workflowLinkPath + 'taskApprovalItems/save',
                                    type: 'post',
                                    dataType: 'json',
                                    data: {
                                        type: type,
                                        approvalItem:body.find("div.layui-show textarea[name=approvalItem]").val(),
                                        flowTypeId:flowTypeId,
                                        modelKey:defKey
                                    },
                                    success: function(data){
                                        if(data.code !== 0){
                                            parent.layer.msg(data.msg, {time: 2500, icon:5});
                                            return false;
                                        }
                                        parent.layer.close(index);
                                        parent.layer.msg(data.msg, {time: 500, icon:6});
                                        common.tableConditionRender("taskApprovalItemsTable","instanceQueryForm",{where:{}},false);
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        layer.alert("删除失败！" + XMLHttpRequest.status);
                                    }
                                });
                            }
                        }

                    },
                });
            };
            function validateLength(approvalItem){
                var approvalList = approvalItem.split('\n');
                for(var i=0 ; i<approvalList.length;i++){
                    if(approvalList[i].length>30){
                        parent.layer.msg('一条常用语不能超过三十个字！', {time: 5000, icon:1});
                        return false;
                    }
                }
                return true;
            };
    })
</script>
</body>
</html>